package com.bamanker.cloudsys.config;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * <p>
 * ssh监听器
 * </p>
 *
 * @author bamanker
 */
@Slf4j
@Component
public class MyContextListener implements ServletContextListener {

    @Value("${ssh:false}")
    public boolean sshSwitch;

    private SSHConnectionConfig sshConnectionConfig;

    public MyContextListener() {
        super();
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("Context initialized ... !");
        if (sshSwitch) {
            try {
                sshConnectionConfig = new SSHConnectionConfig();
                sshConnectionConfig.createSSH();
                log.info("成功建立ssh连接");
            } catch (Throwable e) {
                log.info("SSH连接失败！");
                e.printStackTrace();
                System.exit(0);// 连接失败
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Context destroyed ... !");
        if (sshSwitch) {
            sshConnectionConfig.closeSSH();//断开ssh连接
        }
    }
}
